﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using UserIdentityDemo.Data;
using UserIdentityDemo.Models;


// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace UserIdentityDemo.Controllers
{
    public class HomeController : Controller
    {
        private IAuthorizationService _authorizationService;
        private DataContext _dataContext;

        public HomeController(IAuthorizationService authorizationService, DataContext dataContext)
        {
            _authorizationService = authorizationService;
            _dataContext = dataContext;
        }

        // GET: /<controller>/
        public IActionResult Index()
        {
            return View(_dataContext.Albums);
        }

        public IActionResult Details(int id)
        {
            var album = _dataContext.Albums.FirstOrDefault(a => a.Id == id);
            if (album == null)
            {
                return new NotFoundResult();
            }
            return View(album);
        }

        [Authorize(Policy = PolicyNames.AdministratorsOnly)]
        public async Task<IActionResult> Edit(int id)
        {
            var album = _dataContext.Albums.FirstOrDefault(a => a.Id == id);
            if (album == null)
            {
                return new NotFoundResult();
            }

            if (await _authorizationService.AuthorizeAsync(
                User,
                album,
                PolicyNames.CanEditAlbum))
            {
                return View(album);
            }

            return new ChallengeResult();
        }

        [Authorize(Policy = PolicyNames.AdministratorsOnly)]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(Album album)
        {
            var existingAlbum = _dataContext.Albums.FirstOrDefault(a => a.Id == album.Id);
            if (existingAlbum == null)
            {
                return new NotFoundResult();
            }

            if (await _authorizationService.AuthorizeAsync(
                User,
                existingAlbum,
                PolicyNames.CanEditAlbum))
            {
                _dataContext.Albums.Update(album);
                _dataContext.SaveChanges();
                return View(album);
            }

            return RedirectToAction("Details", new {id = album.Id});
        }

        public IActionResult Error()
        {
            return View();
        }
    }
}